package bloxorz;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.InputStreamReader;
import java.io.IOException;
import java.util.Properties;

public class SICStus implements Runnable {

	private Process process;
	private String command;
	private int port = -1;
	private boolean isShutdown = false;
	
	public SICStus() {
		try {
			Properties prop = new Properties();
			prop.load(new FileReader("bloxorz.properties"));
			String path = prop.getProperty("path");
			String file = prop.getProperty("file");
			command = path + " -l " + file;
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * Execucao do servidor, numa thread 'a parte.
	 */
	public void run() {
		try {
			process = Runtime.getRuntime().exec(command);
			
			//Obter STDERR do processo
			BufferedReader err =
				new BufferedReader(
					new InputStreamReader(process.getErrorStream()));
			
			//E' no STDERR que o porto escolhido pelo SICStus vai ser escrito 
			for (String line = err.readLine(); line != null; line = err.readLine()) {
				// TODO Tirar os prints de compilacao quando tudo bulir.
				if (line.startsWith("port: ")) {
					port = Integer.parseInt(line.substring(6));
					synchronized(this) {
						notify();
					}
				} else {
					System.out.println(line);
				}
			}
			
		} catch (Exception e) {
			e.printStackTrace();
			
		} finally {
			synchronized(this) {
				isShutdown = true;
				notify();
			}
		}
	}
	
	public synchronized int getPort(int timeout) throws InterruptedException {
		if (port == -1) {
			wait(timeout);
		}
		return port;
	}

	public synchronized boolean waitForShutdown(int timeout) throws InterruptedException {
		if (!isShutdown) {
			wait(timeout);
		}
		return isShutdown;
	}
	
	public void shutdown() {
		if (process != null)
			process.destroy();
	}
}
